/**
 * 
 */
package com.licg.chatroom.dwrextents;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.event.ScriptSessionEvent;
import org.directwebremoting.event.ScriptSessionListener;
import org.directwebremoting.impl.DefaultScriptSessionManager;

/**
 * @author li_cguang
 * 
 */
public class CoustemDefaultScriptSessionManager extends
		DefaultScriptSessionManager {
	private final static Log log = LogFactory
			.getLog(CoustemDefaultScriptSessionManager.class);

	public CoustemDefaultScriptSessionManager() {
		addScriptSessionListener(new ScriptSessionListener() {
			/**
			 * 如果用户已经登录，则添加用户信息，否则不作处理
			 * @see org.directwebremoting.event.ScriptSessionListener#sessionCreated(org.directwebremoting.event.ScriptSessionEvent)
			 */
			public void sessionCreated(ScriptSessionEvent event) {
				if (log.isDebugEnabled()) {
					log.debug(("ScriptSessionCreated"));
				}
				ScriptSession scriptSession = event.getSession(); // 获取新创建的SS
				HttpSession httpSession = WebContextFactory.get().getSession();// 获取构造SS的用户的HttpSession
				if (httpSession != null) {
					Object usernameObj = httpSession.getAttribute("username");
					if (usernameObj != null) {
						scriptSession.setAttribute("username",usernameObj);// 此处将username和scriptSession绑定
						userNameScriptSessions.put((String) usernameObj, scriptSession);
					}
				}
			}

			/**
			 * 销毁
			 * @see org.directwebremoting.event.ScriptSessionListener#sessionDestroyed(org.directwebremoting.event.ScriptSessionEvent)
			 */
			public void sessionDestroyed(ScriptSessionEvent event) {
				if (log.isDebugEnabled()) {
					log.debug(("ScriptSessionDestroyed"));
				}
				ScriptSession scriptSession = event.getSession(); // 获取创建的SS
				Object usernameObj =scriptSession.getAttribute("username");
				if(usernameObj!=null){
					if(userNameScriptSessions.containsKey(usernameObj)){
						   userNameScriptSessions.remove(usernameObj);
				   }
				   scriptSession.removeAttribute("username");
				}
				
			}
		});  
	}
	
	/**
	 * 存放用户名与ScriptSession的map
	 */
	public static Map<String,ScriptSession> userNameScriptSessions=new ConcurrentHashMap<String,ScriptSession>();
	
	/**
	 * 只有已经登陆的用户的session才有效
	 * @see org.directwebremoting.impl.DefaultScriptSessionManager#getAllScriptSessions()
	 */
	public Collection<ScriptSession> getAllScriptSessions(){
		 return userNameScriptSessions.values();
	 }
	
	
}
